package net.qiqb.subclass;

import net.bytebuddy.ByteBuddy;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;

import static net.bytebuddy.matcher.ElementMatchers.isDeclaredBy;

public class MainTest1 {
    public static void main(String[] args) throws IllegalAccessException, InstantiationException {
        // 使用 ByteBuddy 创建代理类，拦截 Order 类的构造器并返回 SubOrder 对象
        Order order = new ByteBuddy()
                .subclass(Order.class)
                .method(isDeclaredBy(Object.class))
                .intercept(Advice.to(SubOrderInterceptor.class))
                .make()
                .load(Order.class.getClassLoader(), ClassLoadingStrategy.Default.INJECTION)
                .getLoaded()
                .newInstance();

        // 使用代理对象创建 Order 对象
        Order actualOrder = new Order();
        actualOrder.process(); // 正常的 Order 对象行为

        // 使用代理对象创建 SubOrder 对象
        SubOrder actualSubOrder = new SubOrder();
        actualSubOrder.process(); // 正常的 SubOrder 对象行为
    }

    public static class Order {
        public void process() {
            System.out.println("Processing Order");
        }
    }

    public static class SubOrder extends Order {
        // SubOrder 类可以有自己的特定实现
    }

    public static class SubOrderInterceptor {
        @Advice.OnMethodExit
        @RuntimeType
        public static Object onExit(@Advice.Return String originalReturnValue) {
            // 在方法退出时，返回一个不同类型的值
            return "Modified Value: " + originalReturnValue;
        }
    }
}
